package com.mingzhi.alibaba.demo.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/chat")
public class ChatClientController {

    /*private final ChatClient chatClient;

    public ChatClientController(ChatClient.Builder chatClient) {
        this.chatClient = chatClient.build();
    }*/

    @Resource
    private ChatClient chatClient;

    @GetMapping("/call")
    public String chat(String message) {
        return this.chatClient.prompt()
                .user(message)
                .call()
                .content();
    }

    //流式响应
    @GetMapping(value = "/stream", produces = "text/html;charset=utf-8")
    public Flux<String> stream(String message) {
        return this.chatClient.prompt()
                .user(message)
                .stream()
                .content();
    }


    //返回实体类
    record ActorFilms(String actor, List<String> movies) {
    }

    @GetMapping("/entity")
    public String entity(String message) {
        return this.chatClient.prompt()
                .user(String.format("请生成演员%s的作品", message))
                .call()
                .entity(ActorFilms.class)
                .toString();
    }

    @GetMapping("/generationRecipe")
    public List<ActorFilms> generationRecipe() {
        List<ActorFilms> actorFilms = chatClient.prompt()
                .user("Generate the filmography of 5 movies for Tom Hanks and Bill Murray.")
                .call()
                .entity(new ParameterizedTypeReference<List<ActorFilms>>() {
                });
        return actorFilms;
    }

    /**
     * 先找聊天工具（chatClient）说 "我要发消息了"（prompt ()）
     * 告诉工具一些背景设置："注意啊，这里有个参数叫 'word'，值是 xxx"（system (...)）
     * 然后把用户说的话（message）传给工具
     * 让工具赶紧把这些东西发给 AI 服务器（call ()）
     * 最后从 AI 的回复里，把有用的文字内容拿出来（content ()）
     *
     * @param message
     * @param word
     * @return
     */
    @GetMapping("/word")
    Map<String, String> completion(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message, String word) {
        return Map.of(
                "completion",
                chatClient.prompt()
                        .system(sp -> sp.param("word", word))
                        .user(message)
                        .call()
                        .content());
    }

}
